package com.study.log.service.impl;

import cn.hutool.extra.servlet.ServletUtil;
import com.study.log.enums.LogType;
import com.study.log.event.LogEvent;
import com.study.log.event.LoginEvent;
import com.study.log.event.LogoutEvent;
import com.study.log.repository.dao.LogDao;
import com.study.log.repository.model.LogDO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * 异步日志
 */
@Slf4j
@Service
public class LogServiceImpl {

    @Autowired
    LogDao logDao;

    /**
     * 业务日志
     *
     * @param logEvent
     */
    @Async
    @EventListener(LogEvent.class)
    public void handlerEvent(LogEvent logEvent) {
        LogDO logDO = logEvent.getLogDO();
        logDao.insert(logDO);
    }

    /**
     * 登录日志
     *
     * @param loginEvent
     */
    @Async
    @EventListener(LoginEvent.class)
    public void handlerLoginEvent(LoginEvent loginEvent) {
        LogDO build = build(loginEvent.getRequest(), loginEvent.getUserUuid(), loginEvent.getStoreUuid(), loginEvent.getToken());
        build.setType(LogType.LOGIN);
        logDao.insert(build);
    }

    /**
     * 退出日志
     *
     * @param logoutEvent
     */
    @Async
    @EventListener(LogoutEvent.class)
    public void handlerLogoutEvent(LogoutEvent logoutEvent){
        LogDO build = build(logoutEvent.getRequest(), logoutEvent.getUserUuid(), logoutEvent.getStoreUuid(), logoutEvent.getToken());
        build.setType(LogType.LOGOUT);
        logDao.insert(build);
    }

    private LogDO build(HttpServletRequest request, String userUuid, String storeUuid, String token) {

        LogDO logDO = new LogDO();
        logDO.setUserUuid(userUuid);
        logDO.setStoreUuid(storeUuid);
        logDO.setToken(token);
        if (request != null) {
            logDO.setIp(ServletUtil.getClientIP(request));
            log.info("ip地址："+ServletUtil.getClientIP(request));
        }
        return logDO;
    }

}
